package com.common.user.service;

import java.util.HashSet;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import com.common.user.domain.Permission;
import com.common.user.domain.Role;
import com.common.user.domain.User;

@Component("rbacService")
public class RbacService {

	@Autowired
	private UserService userService;

	private AntPathMatcher antPathMatcher = new AntPathMatcher();

	public boolean hasPermission(HttpServletRequest request) {

		User user = userService.getCurrentUser(request);

		boolean hasPermission = false;
		
		if (user != null) {
			Set<Permission> permissions = new HashSet<>();
			
			for(Role role : user.getRoles()) {
				permissions.addAll(role.getPermissions());
			}

			for (Permission permission : permissions) {
				if (antPathMatcher.match(permission.getUrl(), request.getRequestURI())) {
					hasPermission = true;
					break;
				}
			}
		}
		return hasPermission;
	}
}